package blt.app_core.api.base;

import android.text.TextUtils;

import java.io.IOException;

import blt.app_core.log.Logger;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xgp on 2017/6/22.
 */
public class LoginInterceptor implements Interceptor {
    private String userId;
    private String cookie;

    public LoginInterceptor(String userId, String cookie) {
        this.userId = userId;
        this.cookie = cookie;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();

        if(TextUtils.isEmpty(userId)||TextUtils.isEmpty(cookie)){
            Logger.d("userId or cookie is null,should login");
            return null;
        }


        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host()).addQueryParameter("userId", userId);

        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body()).header("userCookieName", cookie)
                .url(authorizedUrlBuilder.build())
                .build();

        return chain.proceed(newRequest);
    }
}
